﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace ESAM_Assignment_3
{
    public class Encryption
    {
        // Encrypt a Querystring
        public static string EncryptQueryString(string stringToEncrypt)
        {
            DESCryptoServiceProvider des = Global.DESCrypto;

            try
            {
                
                using (DESCryptoServiceProvider oDESCrypto = new DESCryptoServiceProvider())
                {
                    byte[] inputByteArray = Encoding.UTF8.GetBytes(stringToEncrypt);
                    MemoryStream oMemoryStream = new MemoryStream();
                    CryptoStream oCryptoStream = new CryptoStream(oMemoryStream,
                    oDESCrypto.CreateEncryptor(des.Key, des.IV), CryptoStreamMode.Write);
                    oCryptoStream.Write(inputByteArray, 0, inputByteArray.Length);
                    oCryptoStream.FlushFinalBlock();
                    return Convert.ToBase64String(oMemoryStream.ToArray());
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        // Decrypt a Querystring
        public static string DecryptQueryString(string stringToDecrypt)
        {
            DESCryptoServiceProvider des = Global.DESCrypto;

            if (stringToDecrypt != null) { 
                stringToDecrypt = stringToDecrypt.Replace(" ", "+"); 
            }
            byte[] inputByteArray = new byte[stringToDecrypt.Length];

            try
            {
                inputByteArray = Convert.FromBase64String(stringToDecrypt);
                MemoryStream ms = new MemoryStream();
                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(des.Key, des.IV), CryptoStreamMode.Write);
                cs.Write(inputByteArray, 0, inputByteArray.Length);
                cs.FlushFinalBlock();
                Encoding encoding = Encoding.UTF8;
                return encoding.GetString(ms.ToArray());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
